<template>
  <div class="app-container">
    <!-- 添加生产物料信息对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :close-on-click-modal="false"
      draggable
      width="880px"
      append-to-body
      :before-close="handleClose"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        style="height: 500px"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="客户" prop="cusId">
              <el-select
                v-model="form.cusId"
                placeholder="请选择客户"
                @change="selectBigLbm"
              >
                <el-option
                  v-for="dict in cus"
                  :key="dict.cusId"
                  :label="dict.cusCode + dict.cusName"
                  :value="{ value: dict.cusId, label: dict.cusCode }"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="大分类" prop="bigLbmId">
              <el-select
                v-model="form.bigLbmId"
                placeholder="请选择大分类"
                @change="selectMiddleLbm"
              >
                <el-option
                  v-for="dict in bigLbm"
                  :key="dict.lbmId"
                  :label="dict.lbmLbdm + dict.lbmLbmc"
                  :value="{ value: dict.lbmId, label: dict.lbmLbdm }"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="中分类" prop="middleLbmId">
              <el-select
                v-model="form.middleLbmId"
                placeholder="请选择中分类"
                @change="selectSmallLbm"
              >
                <el-option
                  v-for="dict in middleLbm"
                  :key="dict.lbmId"
                  :label="dict.lbmLbdm + dict.lbmLbmc"
                  :value="{ value: dict.lbmId, label: dict.lbmLbdm }"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="小分类" prop="smallLbmId">
              <el-select
                v-model="form.smallLbmId"
                placeholder="请选择小分类"
                @change="generate"
              >
                <el-option
                  v-for="dict in smallLbm"
                  :key="dict.lbmId"
                  :label="dict.lbmLbdm + dict.lbmLbmc"
                  :value="{ value: dict.lbmId, label: dict.lbmLbdm }"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="12">
          <el-form-item label="物料代码" prop="itmWldm">
            <el-input v-model="form.itmWldm" disabled />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
              <el-form-item label="单价" prop="itmWldm">
                <el-input v-model="form.itmPrice" />
              </el-form-item>
            </el-col> -->
        <el-col :span="12" class="right">
          <el-form-item label="物品品名" prop="itmWlpm">
            <el-input v-model="form.itmWlpm" placeholder="请输入物品品名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="材质" prop="itmCzdm">
            <el-input
              v-model="form.itmCzdm"
              placeholder="请输入材质"
              @input="getContainer"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="right">
          <el-form-item label="颜色" prop="itmYsdm">
            <el-input
              v-model="form.itmYsdm"
              placeholder="请输入颜色"
              @input="getContainer"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="净重" prop="itmJz">
            <el-input v-model="form.itmJz" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="1" class="unit-parent">
          <span class="unit">kg</span>
        </el-col>
        <el-col :span="5">
          <el-form-item label="报价周期" prop="itmEdzq">
            <el-input v-model="form.itmEdzq" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="1" class="unit-parent">
          <span class="unit">s</span>
        </el-col>
        <el-col :span="5">
          <el-form-item label="单位水口" prop="itmSkzl">
            <el-input v-model="form.itmSkzl" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="1" class="unit-parent">
          <span class="unit">kg</span>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单位" prop="itmDw">
            <el-select v-model="form.itmDw" placeholder="请选择单位">
              <el-option
                v-for="dict in itmDwOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="尺寸描述" prop="itmCcms">
            <el-input
              v-model="form.itmCcms"
              placeholder="请输入尺寸描述"
              @input="getContainer"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="right">
          <el-form-item label="客户编码" prop="itmCustwldm">
            <el-input
              v-model="form.itmCustwldm"
              placeholder="请输入客户编码"
              @input="getContainer"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="图纸编号" prop="itmTzbh">
            <el-input v-model="form.itmTzbh" placeholder="请输入图纸编号" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="仓库代码" prop="itmCkdm">
            <el-select v-model="form.itmCkdm" placeholder="请输入仓库代码">
              <el-option
                v-for="dict in storageList"
                :key="dict.storageId"
                :label="dict.storageName"
                :value="dict.storageId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="仓位代码" prop="itmCwdm">
            <el-select v-model="form.itmCwdm" placeholder="请输入仓位代码">
              <el-option
                v-for="dict in storageList"
                :key="dict.storageId"
                :label="dict.storageDefaultstorage"
                :value="dict.storageId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="第二仓库" prop="itmCkdmTwo">
            <el-select
              clearable
              v-model="form.itmCkdmTwo"
              placeholder="请输入仓库代码"
              @change="
                form.itmCwdmTwo = form.itmCkdmTwo;
                form.itmKwdmTwo = form.itmCkdmTwo;
              "
            >
              <el-option
                v-for="dict in efficientStorageLists"
                :key="dict.storageId"
                :label="dict.storageName"
                :value="dict.storageId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="第二仓位" prop="itmCwdmTwo">
            <el-select
              v-model="form.itmCwdmTwo"
              placeholder="请输入仓位代码"
              disabled
            >
              <el-option
                v-for="dict in efficientStorageLists"
                :key="dict.storageId"
                :label="dict.storageDefaultstorage"
                :value="dict.storageId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="机种代码" prop="itmJzdm">
            <!--            <el-input v-model="form.itmJzdm" placeholder="请输入机种代码"/>-->
            <el-select v-model="form.itmJzdm" placeholder="请选择机种代码">
              <el-option
                v-for="dict in jzmList"
                :key="dict.jzmId"
                :label="dict.jzmJzdm"
                :value="dict.jzmJzdm"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="制造车间" prop="itmCj">
            <!--            <el-input v-model="form.itmCj" placeholder="请输入制造车间"/>-->
            <el-select v-model="form.itmCj" placeholder="请选择制造车间">
              <el-option
                v-for="dict in itCarOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="最小包装" prop="itmMinbz">
            <el-input
              v-model="form.itmMinbz"
              type="number"
              @input="handleInput"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标准包装1" prop="itmBzsl1">
            <el-input v-model="form.itmBzsl1" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="18" class="right">
          <el-form-item label="其他信息" prop="itmQtinf">
            <el-input
              v-model="form.itmQtinf"
              placeholder="请输入其他信息"
              @input="getContainer"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标准包装2" prop="itmBzsl2">
            <el-input v-model="form.itmBzsl2" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="物料规格" prop="itmWlgg">
            <el-input v-model="form.itmWlgg" placeholder="请输入物料规格" />
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMateriel,
  addMateriel,
  updateMateriel,
  getFirstChild,
  generateItemCode,
  getStorage,
} from "@/api/project/materiel";
import { getAllCustomer } from "@/api/project/customer";
import { getAreaTree } from "@/api/project/lbm";
import { getAll, getstorageType } from "@/api/repertory/Storage";
import { getAllJzm } from "@/api/project/jzmMstr";

export default {
  data() {
    return {
      materrial_prefix: "",
      efficientStorageLists: [],
      //客户ID
      cusId: null,
      //客户分类
      cus: [],
      //大分类信息
      bigLbm: [],
      //中分类
      middleLbm: [],
      //小分类
      smallLbm: [],
      //仓位信息
      storageList: [],
      //机种信息
      jzmList: [],
      //分类Form
      lbmForm: {},
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产物料信息表格数据
      materielList: [],
      // 弹出层标题
      title: "",
      // 是否弹出新增对话框
      open: true,
      //是否弹出修改对话框
      openStr: false,
      // 单位字典
      itmDwOptions: [],
      //制造车间字典
      itCarOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itmWldm: null,
        itmPmgg: null,
        itmCustwldm: null,
        itmCkdm: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      },
      // 表单参数
      form: {
        itmId: null,
        itmWldm: null,
        itmPrice: null,
        itmWlpm: null,
        itmWlgg: null,
        itmPmgg: null,
        itmCzdm: null,
        itmYsdm: null,
        itmQtinf: null,
        itmMz: null,
        itmJz: 0,
        itmSkzl: 0,
        itmDw: null,
        itmCustwldm: null,
        itmTzbh: null,
        itmCgsx: null,
        itmMinbz: 0,
        itmBzsl1: 0,
        itmBzsl2: 0,
        itmCwdm: null,
        itmCkdm: null,
        itmKwdm: null,
        itmCwdmTwo: null,
        itmCkdmTwo: null,
        itmKwdmTwo: null,
        itmJzdm: null,
        itmCcms: null,
        itmZtbz: null,
        itmEdzq: 0,
        itmTedzp: null,
        itmShry: null,
        itmShrq: null,
        itmPzry: null,
        itmPzrq: null,
        itmJccc1: null,
        itmJccc2: null,
        itmJccc3: null,
        itmJczl: null,
        itmCj: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        cusId: null,
        bigLbmId: null,
        middleLbmId: null,
        smallLbmId: null,
        cusCode: null,
        bigLbmCode: null,
        middleLbmCode: null,
        smallLbmCode: null,
      },
      // 表单校验
      rules: {
        itmWlpm: [
          { required: true, message: "物品品名不能为空", trigger: "blur" },
        ],
        itmWlgg: [
          { required: true, message: "物料规格不能为空", trigger: "blur" },
        ],
        itmDw: [{ required: true, message: "单位不能为空", trigger: "change" }],
        itmMinbz: [
          { required: true, message: "最小包装不能为空", trigger: "blur" },
        ],
        itmCwdm: [
          { required: true, message: "仓位代码不能为空", trigger: "blur" },
        ],
        itmCkdm: [
          { required: true, message: "仓库代码不能为空", trigger: "blur" },
        ],
        cusId: [{ required: true, message: "客户不能为空", trigger: "change" }],
        bigLbmId: [
          { required: true, message: "大分类不能为空", trigger: "change" },
        ],
        middleLbmId: [
          { required: true, message: "中分类不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.init();
    this.getList();
    this.getDicts("sys_unit").then((response) => {
      this.itmDwOptions = response.data;
    });
    //制造车间字典
    this.getDicts("Manufacturing_plant").then((response) => {
      this.itCarOptions = response.data;
    });
    this.getConfigKey("sys.materrial.prefix").then((response) => {
      this.materrial_prefix = response.msg;
    });
    getstorageType(0).then((response) => {
      this.efficientStorageLists = response.data.map((a) => {
        a.listClass = "default";
        a.storageId = "" + a.storageId;
        return a;
      });
    });
  },
  methods: {
    handleClose(done) {
      this.$emit("AddReturn", {});
      this.$parent.openDialog = false;
      //父项清空
      this.$parent.form.bomWldm = null;
      this.$parent.form.itmPmgg = null;
      //子项清空
      this.$parent.childForm.bodZxdm = null;
      this.$parent.childForm.bodPmgg = null;
      done();
    },
    /** 查询生产物料信息列表 */
    getList() {
      this.loading = true;
      listMateriel(this.queryParams).then((response) => {
        this.materielList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.$emit("AddReturn", {});
      this.open = false;
      this.$parent.openDialog = false;
      //父项清空
      this.$parent.form.bomWldm = null;
      this.$parent.form.itmPmgg = null;
      //子项清空
      this.$parent.childForm.bodZxdm = null;
      this.$parent.childForm.bodPmgg = null;
      this.reset();
    },
    cancelStr() {
      this.openStr = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        itmId: null,
        itmWldm: null,
        itmWlpm: null,
        itmWlgg: null,
        itmPmgg: null,
        itmCzdm: null,
        itmYsdm: null,
        itmQtinf: null,
        itmMz: null,
        itmJz: 0,
        itmSkzl: 0,
        itmDw: null,
        itmCustwldm: null,
        itmTzbh: null,
        itmCgsx: null,
        itmMinbz: null,
        itmCwdm: null,
        itmCkdm: null,
        itmKwdm: null,
        itmJzdm: null,
        itmCcms: null,
        itmZtbz: null,
        itmEdzq: 0,
        itmTedzp: null,
        itmShry: null,
        itmShrq: null,
        itmPzry: null,
        itmPzrq: null,
        itmJccc1: null,
        itmJccc2: null,
        itmJccc3: null,
        itmJczl: null,
        itmCj: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        cusId: null,
        bigLbmId: null,
        middleLbmId: null,
        smallLbmId: null,
        cusCode: null,
        bigLbmCode: null,
        middleLbmCode: null,
        smallLbmCode: null,
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    init() {
      getAllCustomer().then((response) => {
        this.cus = response.data;
        getAllJzm().then((res) => {
          this.jzmList = res.data;
        });
        this.reset();
        this.open = true;
        this.title = "添加生产物料信息";
      });
    },
    getContainer() {
      this.form.itmWlgg =
        (this.form.itmCustwldm ? this.form.itmCustwldm + "," : "") +
        (this.form.itmCzdm ? this.form.itmCzdm + "," : "") +
        (this.form.itmYsdm ? this.form.itmYsdm + "," : "") +
        (this.form.itmCcms ? this.form.itmCcms + "," : "") +
        (this.form.itmQtinf ? this.form.itmQtinf + "," : "");
      this.form.itmWlgg = this.form.itmWlgg.slice(
        0,
        this.form.itmWlgg.length - 1
      );
      this.$parent.form.itmPmgg = this.form.itmWlgg;
      this.$parent.childForm.bodPmgg = this.form.itmWlgg;
    },

    /** 查询 大分类 */
    selectBigLbm(data) {
      //查询大分类的话
      this.form.bigLbmId = null;
      this.form.middleLbmId = null;
      this.form.smallLbmId = null;
      this.form.itmCkdm = null;
      this.form.itmCwdm = null;
      this.form.itmWldm = null;
      this.bigLbm = [];
      this.middleLbm = [];
      this.smallLbm = [];
      this.storageList = [];

      getFirstChild(data.value).then((response) => {
        if (response.data.length < 1) {
          this.msgError("无大分类，请前往客户代码分配大分类，否则无法添加物料");

          return;
        }

        this.form.cusCode = data.label;

        this.bigLbm = response.data;
      });
    },

    /** 查询中分类 */
    selectMiddleLbm(data) {
      this.form.middleLbmId = null;
      this.form.smallLbmId = null;
      this.form.itmWldm = null;
      this.middleLbm = [];
      this.smallLbm = [];
      this.form.itmCkdm = null;
      this.form.itmCwdm = null;
      this.storageList = [];

      getAreaTree(data.value).then((response) => {
        if (response.data.length < 1) {
          this.msgError(
            "无中分类，请前往类别代码对应大分类中添加中分类，否则无法添加物料"
          );

          return;
        }
        this.form.bigLbmCode = data.label;

        this.middleLbm = response.data;
      });
    },

    /** 查询小分类 */
    selectSmallLbm(data) {
      this.form.itmWldm = null;
      getAreaTree(data.value).then((response) => {
        if (response.data.length < 1) {
          //TODO 直接生成物料代码
          //开始构建参数
          let wldm =
            this.materrial_prefix +
            "." +
            this.form.cusCode +
            "." +
            this.form.bigLbmCode +
            "." +
            data.label +
            "." +
            "00" +
            ".";
          //向后端发送请求查询最新的对应的物料代码
          generateItemCode(wldm).then((response) => {
            this.form.itmWldm = response.msg;
          });
        }

        this.middleLbmCode = data.label;

        this.smallLbm = response.data;
      });

      //TODO 查询对应的仓位以及储位   如果后期采用仓储系统，这个地方查询的就不是这个接口
      let ppwldm = this.form.cusCode + "." + this.form.bigLbmCode;
      // 荆州定制需求
      if (this.materrial_prefix === "J") {
        const regStr = `${this.form.cusCode}.${this.form.bigLbmCode}.${data.label}`;
        const rulesReg = [
          {
            reg: /^.*?\.6\..*/,
            sort: 10,
            storage: [
              {
                storageCode: "FL",
                storageDefaultstorage: "FL-000-00-00",
                storageFlag: null,
                storageId: 7,
                storageName: "辅料仓",
              },
            ],
          },
          {
            reg: /^.*?\.6\.(01|12)/,
            sort: 50,
            storage: [
              {
                storageCode: "ZX",
                storageDefaultstorage: "ZX-000-00-00",
                storageFlag: null,
                storageId: 17,
                storageName: "纸箱仓",
              },
            ],
          },
          {
            reg: /^.*?\.6\.(02)/,
            sort: 50,
            storage: [
              {
                storageCode: "WJ",
                storageDefaultstorage: "WJ-000-00-00",
                storageFlag: null,
                storageId: 9,
                storageName: "五金仓",
              },
            ],
          },
          {
            reg: /^.*?\.3\.(07|14)/,
            sort: 50,
            storage: [
              {
                storageCode: "DZ",
                storageDefaultstorage: "YL-000-00-00",
                storageFlag: null,
                storageId: 12,
                storageName: "电子仓",
              },
            ],
          },
          {
            reg: /^.*?\.3\.((?!(01|02)).*?)/,
            sort: 60,
            storage: [
              {
                storageCode: "FL",
                storageDefaultstorage: "FL-000-00-00",
                storageFlag: null,
                storageId: 7,
                storageName: "辅料仓",
              },
            ],
          },
        ];
        const rule = rulesReg
          .filter((o) => o.reg.test(regStr))
          .sort((a, b) => b.sort - a.sort);
        console.log(rule);
        if (rule[0]) {
          this.storageList = rule[0].storage;
          this.form.itmCwdm = this.storageList[0].storageId;
          this.form.itmCkdm = this.storageList[0].storageId;
          this.form.itmKwdm = this.storageList[0].storageId;
          return;
        }
      }

      if (this.form.bigLbmCode == "2") {
        if (["02"].includes(data.label)) {
          this.storageList = [
            {
              storageCode: "PBC",
              storageDefaultstorage: "PBC-000-00-00",
              storageFlag: null,
              storageId: 16,
              storageName: "喷涂半成品仓",
            },
          ];
          this.form.itmCwdm = this.storageList[0].storageId;
          this.form.itmCkdm = this.storageList[0].storageId;
          this.form.itmKwdm = this.storageList[0].storageId;
          return;
        }
      }

      getStorage(ppwldm).then((response) => {
        if (response.data.length < 1) {
          this.msgError(
            "该物料绑定的仓位失效或没有绑定仓位，请前往库存管理/仓位分配绑定仓位,否则无法创建该物料"
          );
          return;
        }
        this.storageList = response.data;
        this.form.itmCwdm = this.storageList[0].storageId;
        this.form.itmCkdm = this.storageList[0].storageId;
        this.form.itmKwdm = this.storageList[0].storageId;
      });
    },

    generate(data) {
      this.form.itmWldm = null;
      //TODO 直接生成物料代码
      //开始构建参数
      let wldm =
        this.materrial_prefix +
        "." +
        this.form.cusCode +
        "." +
        this.form.bigLbmCode +
        "." +
        this.middleLbmCode +
        "." +
        data.label +
        ".";

      //向后端发送请求
      generateItemCode(wldm).then((response) => {
        this.form.itmWldm = response.msg;
      });
    },
    handleInput(a) {
      if (a < 0) {
        this.form.itmMinbz = 0;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.itmId != null) {
            updateMateriel(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.openStr = false;
              this.$emit("AddReturn", this.form);
            });
          } else {
            addMateriel(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.$emit("AddReturn", this.form);
            });
          }
          // this.$parent.openDialog = false
        } else {
          // this.$emit('AddReturn', {})
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.unit-parent {
  height: 34px;
}

.unit {
  margin-left: 10px;
  height: 34px;
  line-height: 34px;
}

.unit-button {
  margin-left: 10px;
  height: 38px;
  line-height: 38px;
}
</style>
